import { App } from 'vue';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { RedirectRoute } from '@/router/base';
import { PageEnum } from '@/enums/pageEnum';
import { createRouterGuards } from './guards';
import type { IModuleType } from './types';

const modules = import.meta.glob<IModuleType>('./modules/**/*.ts', { eager: true });

// 为路由添加 ucenter/:uniqueStr 前缀的函数
function addUcenterPrefix(routes: RouteRecordRaw[]): RouteRecordRaw[] {
  return routes.map(route => {
    const newRoute: RouteRecordRaw = {
      ...route,
      path: `/ucenter/:uniqueStr${route.path}`,
    };

    // 处理重定向
    if (route.redirect) {
      if (typeof route.redirect === 'string') {
        newRoute.redirect = (to: any) => `/ucenter/${to.params.uniqueStr}${route.redirect}`;
      } else if (typeof route.redirect === 'function') {
        const originalRedirect = route.redirect;
        newRoute.redirect = (to: any) => {
          const result = originalRedirect(to);
          if (typeof result === 'string') {
            return `/ucenter/${to.params.uniqueStr}${result}`;
          }
          return result;
        };
      }
    }

    // 处理子路由 - 子路由保持相对路径
    if (route.children) {
      newRoute.children = route.children;
    }

    return newRoute;
  });
}

const originalRouteModuleList: RouteRecordRaw[] = Object.keys(modules).reduce((list, key) => {
  const mod = modules[key].default ?? {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  return [...list, ...modList];
}, []);

const routeModuleList: RouteRecordRaw[] = addUcenterPrefix(originalRouteModuleList);

function sortRoute(a: RouteRecordRaw, b: RouteRecordRaw) {
  return ((a.meta?.sort as number) ?? 0) - ((b.meta?.sort as number) ?? 0);
}

routeModuleList.sort(sortRoute);

// 根路径显示引导页面
export const RootRedirectRoute: RouteRecordRaw = {
  path: '/',
  name: 'RootRedirect',
  component: () => import('@/views/guide/index.vue'),
  meta: {
    title: '访问指南',
  },
};

export const RootRoute: RouteRecordRaw = {
  path: '/ucenter/:uniqueStr',
  name: 'Root',
  redirect: (to) => `/ucenter/${to.params.uniqueStr}${PageEnum.BASE_HOME_REDIRECT}`,
  meta: {
    title: 'Root',
  },
};





export const LoginRoute: RouteRecordRaw = {
  path: '/ucenter/:uniqueStr/login',
  name: 'Login',
  component: () => import('@/views/login/index.vue'),
  meta: {
    title: '登录',
  },
};

//需要验证权限
export const asyncRoutes = [...routeModuleList, RedirectRoute];

//普通路由 无需验证权限
export const constantRouter: RouteRecordRaw[] = [
  RootRedirectRoute,
  LoginRoute,
  RootRoute
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRouter,
  strict: false, // 关闭严格模式，允许尾部斜杠的灵活匹配
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 添加异步路由
asyncRoutes.forEach(route => {
  router.addRoute(route);
});

export function setupRouter(app: App) {
  app.use(router);
  // 创建路由守卫
  createRouterGuards(router, asyncRoutes);
}

export default router;
